package com.ds.common.org.expression.person;

import java.util.Stack;

import com.ds.common.expression.ParseException;
import com.ds.common.expression.function.Function;
import com.ds.org.Org;
import com.ds.org.OrgManager;
import com.ds.org.OrgNotFoundException;
import com.ds.org.Person;
import com.ds.server.OrgManagerFactory;

/**
 * <p>
 * Title: JDSORG组织机构中间件
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: jds Copyright (c) 2003-2008
 * </p>
 * <p>
 * Company: www.justdos.net
 * </p>
 * 
 * @author wenzhangli
 * @version 2.0
 */
public class GetPersonByOrg extends Function {
    public GetPersonByOrg() {
	numberOfParameters = 1;
    }

    public void run(Stack stack) throws ParseException {
	checkStack(stack); // check the stack

	stack.push(perform(stack.pop()));
    }

    protected Person[] perform(Object param1) throws ParseException {
	if (param1 == null) {
	    return new Person[0];
	}
	if (param1 instanceof String) {
	    String orgId = (String) param1;
	    OrgManager accountManager = OrgManagerFactory.getOrgManager();
	    Org org = null;
	    try {
		org = accountManager.getOrgByID(orgId);
	    } catch (OrgNotFoundException e) {
		e.printStackTrace();
	    }

	    return (Person[]) org.getPersonList().toArray(new Person[org.getPersonList().size()]);
	}
	if (param1 instanceof Org) {
	    Org org = (Org) param1;

	    return (Person[]) org.getPersonList().toArray(new Person[org.getPersonList().size()]);
	}
	throw new ParseException("Invalid parameter type in:" + this.getClass().getName() + ", param1 is " + param1.getClass().getName());
    }
}
